<template>
  <div :class="ns.b()">
    <NavBar v-if="!isXcx()" @onBack="toBack"></NavBar>
    <main :class="ns.e('main')">
      <img :class="ns.em('main', 'topic')" :src="topicBg" alt="" />
      <div :class="ns.em('main', 'info')">
        <div class="money">
          ￥
          <span class="font-gilroy-bold">999.00</span>
        </div>

        <div class="time">
          剩余
          <Countdown :time="10000" class="count-down" @finish="onFinish" />
          交易关闭
        </div>
        <template v-if="orderInfo?.orderType !== OrderType.TRANSFER">
          <template v-if="orderInfo?.remainingExpireTime && !countDownOver">
            <div
              v-if="orderInfo?.goodsTitles"
              class="text-[24px] text-[#999] text-center mt-[24px] leading-[34px] flex"
            >
              <span class="title-width line-clamp-1">{{ orderInfo?.goodsTitles[0] }}</span
              >{{ orderInfo?.goodsTitles.length > 1 ? '等' : '' }}共计
              <span class="text-[#E62129] px-[4px]"> {{ orderInfo?.goodsTitles?.length }} </span>
              件商品
            </div>
          </template>
          <div v-else>交易关闭</div>
        </template>

        <!-- 支付方式 -->
        <div class="mode">
          <p class="mode-title">支付方式</p>

          <payModel @change="onPayChange" @updateConfig="getWeChatAppId"></payModel>
        </div>
      </div>
    </main>
    <footer :class="[ns.e('footer'), 'safe-area']">
      <button :class="ns.em('footer', 'button')" @click="onPay">立即支付</button>
    </footer>
  </div>
</template>
<script setup lang="ts">
//components
import Countdown from '../../../shared/components/Countdown/index.vue'
import NavBar from '../components/navBar.vue'
import payModel from '../components/payMode.vue'
// hooks
import { useNamespace } from '../../../shared/index'
import { useOrderEffect } from '../../../shared/hooks/useOrderEffect'
import { usePayEffect } from '../../../shared/hooks/usePayEffect'
import { useThemeEffect } from '../hooks/useTheme'

// enums
import { OrderType, OrderSource, PayMode } from '../../../shared/enums'
// img
import topicBg from '@/assets/images/topic-bg.png'
// utils
import { isWeChat, isXcx } from '@kukefe/kkutils'
import { debounceFn } from '../../../shared/utils'

import { getWxAppId } from '../../../shared/apis/index'

const { code, appId, orderSn, orderSns, lesseeId, redirectUri, port } = useRoute().query as Record<
  string,
  string | any
>
const ns = useNamespace('m-cashiering')

// 获取主题色
useThemeEffect()

const { orderInfo, excludeZeroOrder } = useOrderEffect()

/**
 * @description 倒计时结束
 */
const countDownOver = ref(false)
const onFinish = (): void => {
  countDownOver.value = true
}

const settleMode = ref(
  isXcx() ? PayMode.WX_MINI : isWeChat() && !isXcx() ? PayMode.WX_JSAPI : PayMode.WX_H5
)

const onPayChange = (mode: PayMode) => {
  settleMode.value = mode
}
/**
 * @description 支付
 */
const { handlePay } = usePayEffect({
  orderSource: OrderSource.KukeOnlineOrder,
  excludeZeroOrder,
  settleMode: settleMode
})

const toAuth = debounceFn(
  async () => {
    // 购物车多订单
    const orderUrl = orderSn ? `orderSn=${orderSn}` : `orderSns=${orderSns}`
    const { VITE_WE_CHART_AUTH_URL } = import.meta.env

    const baseUrl = VITE_WE_CHART_AUTH_URL //window.location.origin
    const url = encodeURIComponent(
      `${baseUrl}/cashier/?${orderUrl}&appId=${appId}&lesseeId=${lesseeId}&redirectUri=${redirectUri}&port=${window.location.port}`
    )
    const href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appIdStr.value}&redirect_uri=${url}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`
    window.location.href = href
  },
  2000,
  true
)

/**
 * @description 立即支付
 */
const onPay = () => {
  // 判断是否是在微信环境 且不是小程序内 如果参数中没有code 需要去授权  然后再支付

  if (isXcx()) {
    handlePay()
  } else if (isWeChat() && !isXcx() && !code) {
    toAuth()
  } else if (isWeChat() && code) {
    handlePay()
  }
  if (!isWeChat()) {
    handlePay()
  }
}

/**
 * @description 获取微信appid
 */
const appIdStr = ref('')
const getWeChatAppId = async () => {
  if (code) return
  const { data } = await getWxAppId({
    clientType: isXcx() ? PayMode.WX_MINI : PayMode.WX_H5,
    relatedId: appId
  })

  appIdStr.value = data.appId
}

// 返回商品详情
const toBack = () => {
  const url = redirectUri
  const encodeUrl = decodeURIComponent(url)
  const backUrl = new URL(encodeUrl)
  window.location.replace(`${backUrl.origin}`)
}

onMounted(async () => {
  // 授权回来 如果是微信环境 并且不是小程序  并且有code 就直接吊起支付
  if (isWeChat() && !isXcx() && code) {
    // 如果有prot的话直接http://localhost:{prot}携带code等参数从定向到开发地址
    if (port) {
      const href = `http://localhost:${port}${window.location.search.replace(/&port=\d+/, '')}`
      location.replace(href)
      return
    }
    handlePay()
  }
})
</script>
<style lang="scss">
.kc-m-cashiering {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  &__main {
    position: relative;
    height: calc(100vh - 2.8rem);

    &--topic {
      height: 450px;
    }
    &--info {
      position: absolute;
      top: 0;
      width: 100%;
      padding: 96px 24px 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      .money {
        color: #e62129;
        font-size: 36px;
        font-weight: 600;
        line-height: 58px;
        margin-bottom: 16px;
        span {
          font-size: 58px;
          font-weight: 600;
        }
      }
      .time {
        display: flex;
        align-items: center;
        color: #111;
        font-size: 24px;
        font-weight: 400;
        .count-down {
          font-size: 28px;
          padding: 0 4px;
          span {
            width: 40px !important;
          }
        }
      }

      .mode {
        padding: 0 24px 24px 24px;
        background: #f7f7f7;
        border-radius: 16px;
        margin-top: 96px;
        overflow: hidden;
        width: 100%;
        &-title {
          margin-bottom: 24px;
          color: #111;
          font-size: 32px;
          font-weight: 600;
          height: 108px;
          line-height: 108px;
        }
      }
    }
  }
  &__footer {
    height: 132px;
    box-shadow: inset 0 0.01rem #eee;
    display: flex;
    justify-content: center;
    &--button {
      height: 96px;
      width: 702px;
      margin-top: 12px;
      background: var(--kc-system-theme-color);
      font-size: 32px;
      line-height: 96px;
      color: #fff;
      font-weight: 500;
      border-radius: 24px;
    }
  }
}
</style>
